package com.epam.DAO.JPA;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import com.epam.DAO.GenericDAO;

public abstract class GenericDAOJPA<T> implements GenericDAO<T> {

	private Class<T> type;
	protected EntityManagerFactory emf;
		
	protected GenericDAOJPA(Class<T> type) {
		this.type = type;
		emf = Persistence.createEntityManagerFactory("CarRent2");
	}
	
	public EntityManager getEntityManager(){
		return emf.createEntityManager();
	}
	
	public void setEntityManagerFactory(EntityManagerFactory emf){
		this.emf = emf;
	}
	
	public void create(T newInstance) {
		EntityManager em = getEntityManager(); 
		em.getTransaction().begin();
		em.persist(newInstance);
		em.getTransaction().commit();
		em.close();
	}

	public T read(int id) {
		EntityManager em = getEntityManager(); 
		T object = em.find(type, id);
		em.close();
		return object;
	}

	public void update(T transientObject) {
		EntityManager em = getEntityManager(); 
		em.getTransaction().begin();
		em.merge(transientObject);
		em.getTransaction().commit();
		em.close();
	}

	public void delete(T persistentObject) {
		EntityManager em = getEntityManager(); 
		em.getTransaction().begin();
		em.merge(persistentObject);
		em.remove(persistentObject);
		em.getTransaction().commit();
		em.close();
	}
			
}
